package com.szzg10.webservice.chapter3;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.ws.LogicalMessage;
import javax.xml.ws.handler.LogicalHandler;
import javax.xml.ws.handler.LogicalMessageContext;
import javax.xml.ws.handler.MessageContext;

import com.szzg10.webservice.chapter3.wsimport.CountRabbits;
import com.szzg10.webservice.chapter3.wsimport.ObjectFactory;

public class ArgHandler implements LogicalHandler<LogicalMessageContext> {

	@Override
	public boolean handleMessage(LogicalMessageContext ctx) {
		
		Boolean request_flag = (Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		
		if(request_flag) {
			LogicalMessage message = ctx.getMessage();
			
			try {
				JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
				
				Object payload = message.getPayload(jaxbContext);
				if(payload instanceof JAXBElement) {
					Object element = ((JAXBElement)payload).getValue();
					
					if(element instanceof CountRabbits) {
						CountRabbits countRabbits = (CountRabbits)element;
						
						int i = countRabbits.getArg0();
						if(i < 0) {
							i = Math.abs(i);
							countRabbits.setArg0(i);
							
							((JAXBElement)payload).setValue(countRabbits);
							message.setPayload(payload, jaxbContext);
						}
					}
				}
				
			} catch (JAXBException e) {
				e.printStackTrace();
			}
			
		}
		
		return true;
	}
	
	@Override
	public void close(MessageContext arg0) {}

	@Override
	public boolean handleFault(LogicalMessageContext arg0) {
		return false;
	}

}
